package com.scisoft.scan.control.pack;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.data.pack.PackBoxBean;
import com.scisoft.scan.data.pack.PackDetailBean;
import com.scisoft.scan.data.pack.PackInfoBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Pack;

import java.util.ArrayList;
import java.util.List;

public class PackDetailActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private ImageView iv_search;//搜索按钮
    private TextView bt_packed;
    private TextView bt_unpack;
    private ListView lv_data;
    private View v_pack;
    private View v_unpack;
    private LinearLayout linearLayout;//标题头
    private TextView tv_statis;//箱号
    private TextView tv_submit;//完成按钮
    private TextView tv_info;//打包情况信息
    private TextView tv_customerPhone;//客户名称和电话
    private TextView tv_customerAdress;//客户地址
    private TextView tv_opinfo;//操作员和操作时间
    private TextView tv_remark;//备注
    private ClearEditText et_bar;

    private PackInfoBean packInfobean;//主界面客户信息
    private String flag;//当前订单的状态，从主表单带过来，注：1 未打包 2 打包中 3已打包

    //没有打包的配件单全部
    private List<PackDetailBean> notPackedDetailList;
    //当前过滤后的配件，列表操作的是这个
    private List<PackDetailBean> filterNotPackedDetailList;
    //已经打包的配件单
    private List<PackBoxBean> packBoxBeanList;
    //当前列表 1 待打包 2 已打包
    private int currentState = 1;
    //当前箱号
    private int currentBox = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//即隐藏标题栏
        setContentView(R.layout.activity_pack_detail);

        //初始化扫码
        init();

        //参数传递
        Intent intent = getIntent();
        //客户信息
        packInfobean = (PackInfoBean) intent.getSerializableExtra("data");
        //订单状态
        flag = intent.getStringExtra("flag");


        //左侧页签组
        linearLayout = findViewById(R.id.layout_bar_group);
        //每页的内容
        lv_data = findViewById(R.id.lv_data);
        lv_data.setOnItemClickListener(new ListViewClick());
        bt_packed = findViewById(R.id.bt_packed);
        bt_unpack = findViewById(R.id.bt_unpack);
        v_pack = findViewById(R.id.v_pack);
        v_unpack = findViewById(R.id.v_unpack);
        tv_statis = findViewById(R.id.tv_statis);
        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*if (notPackedDetailList != null && notPackedDetailList.size() > 0) {
                    Toast.makeText(getApplicationContext(), "还有未打包数据，不能提交完成。", Toast.LENGTH_LONG).show();
                    return;
                }*/
                CommonUtil.showPress(PackDetailActivity.this);
                ComplitePackTask complitePackTask = new ComplitePackTask(PackDetailActivity.this);
                complitePackTask.execute();
            }
        });
        //设置订单的一些基础信息
        tv_info = findViewById(R.id.tv_info);
        tv_info.setText(packInfobean.detail);
        tv_customerPhone = findViewById(R.id.tv_customerPhone);
        tv_customerPhone.setText("单    号：" + packInfobean.orderNo);
        tv_customerAdress = findViewById(R.id.tv_customerAdress);
        tv_customerAdress.setText("仓    库："+ packInfobean.depotName);
        tv_opinfo = findViewById(R.id.tv_opinfo);
        tv_opinfo.setText("打包人：" + packInfobean.operator);
        tv_remark = findViewById(R.id.tv_remark);
        tv_remark.setText("备    注：" + packInfobean.remark);
        et_bar = findViewById(R.id.et_bar);
        et_bar.setText("");
        //页签切换
        bt_packed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_unpack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(PackDetailActivity.this, PackInfoActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
                finish();
            }
        });
        //搜索过滤
        iv_search = findViewById(R.id.iv_search);
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                filterData(et_bar.getUpperText().toString());
                setButton(bt_unpack);
            }
        });
        //查询数据
        queryData();
    }

    //初始化界面数据
    private void queryData() {
        CommonUtil.showPress(this);
        QueryPackDetailTask queryPackInfoTask = new QueryPackDetailTask(PackDetailActivity.this);
        queryPackInfoTask.execute();
    }

    //过滤(配件列表包含过滤条件)
    private void filterData(String filter) {
        filterNotPackedDetailList = new ArrayList<>();
        if (filter != null && filter != "") {
            if (notPackedDetailList != null) {
                for (int i = 0; i < notPackedDetailList.size(); i++) {
                    PackDetailBean bean = notPackedDetailList.get(i);
                    if (bean.partNo!=null && bean.partNo.contains(filter)) {
                        filterNotPackedDetailList.add(bean);
                    }else  if (bean.partCode!=null && bean.partCode.contains(filter)) {
                        filterNotPackedDetailList.add(bean);
                    }else  if (bean.partName!=null && bean.partName.contains(filter)) {
                        filterNotPackedDetailList.add(bean);
                    }
                }
            }
        } else {
            if (notPackedDetailList != null) {
                for (int i = 0; i < notPackedDetailList.size(); i++) {
                    PackDetailBean bean = notPackedDetailList.get(i);
                    filterNotPackedDetailList.add(bean);
                }
            }
        }
    }

    //设置tab页的颜色
    private void setButton(View v) {
        List<PackDetailBean> packDetailBeans = null;
        if (v.getId() == bt_packed.getId()) {
            v_pack.setVisibility(View.VISIBLE);
            v_unpack.setVisibility(View.INVISIBLE);
            bt_packed.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_unpack.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            currentState = 2;
            packDetailBeans = packBoxBeanList.get(currentBox).packDetailBeanList;
        } else {
            currentState = 1;
            v_pack.setVisibility(View.INVISIBLE);
            v_unpack.setVisibility(View.VISIBLE);
            bt_packed.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_unpack.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            packDetailBeans = filterNotPackedDetailList;
        }
        PackDetailAdapter adapter = new PackDetailAdapter(flag,currentState,packDetailBeans, PackDetailActivity.this);
        lv_data.setAdapter(adapter);
    }

    //绑定数据
    @SuppressLint("ResourceAsColor")
    private void BindBox(final Context context) {
        //清空
        et_bar.setText("");
        filterData("");
        linearLayout.removeAllViews();
        int width = linearLayout.getMeasuredWidth();
        //重新加载控件
        TextView bt1 = new TextView(this);
        bt1.setBackground(getResources().getDrawable(R.drawable.edit_bg_button_state_lightblue));
        bt1.setTextColor(getResources().getColor(R.color.white));
        bt1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        bt1.setGravity(Gravity.CENTER);
        bt1.setText("+");
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //增加判断，有空箱子的时候，不允许再新增
                boolean hasEmptyBox = false;
                for(int i = 0;i<packBoxBeanList.size();i++) {
                    PackBoxBean packBoxBean = packBoxBeanList.get(i);
                    if ("-1".equals(packBoxBean.packingId)) {
                        hasEmptyBox = true;
                        break;
                    }
                }
                if(hasEmptyBox) {
                    Toast.makeText(getApplicationContext(), "有空箱时不能新增", Toast.LENGTH_LONG).show();
                    return;
                }
                PackBoxBean packBoxBean = new PackBoxBean();
                packBoxBean.packingId = "-1";
                packBoxBean.packingNo = "打包提交后自动生成";
                packBoxBeanList.add(packBoxBean);
                currentBox = packBoxBeanList.size() - 1;
                BindBox(context);
                //CommonUtil.showPress(context);
                //AddPackBoxTask addPackBoxTask = new AddPackBoxTask(PackDetailActivity.this);
                //addPackBoxTask.execute();
            }
        });
        TextView bt2 = new TextView(this);
        bt2.setBackground(getResources().getDrawable(R.drawable.edit_bg_button_state_lightblue));
        bt2.setTextColor(getResources().getColor(R.color.white));
        bt2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        bt2.setGravity(Gravity.CENTER);
        bt2.setText("－");
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //只有一个箱号不能删除
                if(packBoxBeanList.size()==1) {
                    Toast.makeText(getApplicationContext(), "只有一个箱号时不能删除", Toast.LENGTH_LONG).show();
                    return;
                }
                String packingId = packBoxBeanList.get(currentBox).packingId;
                //如果还没有上传的箱号，直接删除
                if("-1".equals(packingId)){
                    packBoxBeanList.remove(currentBox);
                    currentBox = packBoxBeanList.size() - 1;
                    BindBox(context);
                }else {
                    //非空箱，需要询问再上传
                    AlertDialog alertDialog = new AlertDialog.Builder(PackDetailActivity.this)
                            //.setTitle("这是标题")
                            .setMessage("此箱已有打包配件，是否删除?")
                            //.setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    CommonUtil.showPress(context);
                                    DeletePackBoxTask deletePackBoxTask = new DeletePackBoxTask(PackDetailActivity.this);
                                    deletePackBoxTask.execute();
                                }
                            })
                            .setNegativeButton("否", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    return;
                                }
                            })
                            .create();
                    alertDialog.show();
                }

            }
        });
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, width);
        linearLayout.addView(bt1, layoutParams);
        int count = packBoxBeanList.size();
        for (int i = 0; i < count; i++) {
            TextView button = new TextView(this);
            button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            button.setGravity(Gravity.CENTER);
            button.setText(i + 1 + "");
            button.setId(i + 1);
            if (i == currentBox) {
                button.setBackground(getResources().getDrawable(R.drawable.edit_bg_button_state_white));
                button.setTextColor(getResources().getColor(R.color.bg_button));
            } else {
                button.setBackground(getResources().getDrawable(R.drawable.edit_bg_button_state_gray));
                button.setTextColor(getResources().getColor(R.color.black));
            }
            button.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onClick(View v) {
                    TextView button = (TextView) v;
                    currentBox = Integer.parseInt(button.getText().toString()) - 1;
                    tv_statis.setText("箱号:" + packBoxBeanList.get(currentBox).packingNo);
                    bt_packed.setText("已打包(" + String.valueOf(currentBox + 1) + "号箱)");
                    button.setTextColor(getResources().getColor(R.color.bg_button));
                    button.setBackground(getResources().getDrawable(R.drawable.edit_bg_button_state_white));
                    int m = button.getId();
                    int buttonCount = packBoxBeanList.size();
                    for (int j = 0; j < buttonCount; j++) {
                        if (j + 1 != m) {
                            TextView tmpbutton = linearLayout.findViewById(j + 1);
                            tmpbutton.setBackground(getResources().getDrawable(R.drawable.edit_bg_button_state_gray));
                            tmpbutton.setTextColor(getResources().getColor(R.color.black));
                        }
                    }
                    if (currentState == 1)
                        setButton(bt_unpack);
                    else
                        setButton(bt_packed);
                }
            });
            linearLayout.addView(button, layoutParams);
        }
        linearLayout.addView(bt2, layoutParams);

        if (currentBox < 0)
            currentBox = 0;
        tv_statis.setText("箱号:" + packBoxBeanList.get(currentBox).packingNo);
        bt_packed.setText("已打包(" + String.valueOf(currentBox + 1) + "号箱)");

        if (currentState == 1)
            setButton(bt_unpack);
        else
            setButton(bt_packed);

        //判断是否已经全部打包，如果全部打包自动提示用户是否调用全部打包的操作。
        if (notPackedDetailList.size() == 0) {
            AlertDialog alertDialog = new AlertDialog.Builder(PackDetailActivity.this)
                    //.setTitle("这是标题")
                    .setMessage("全部配件都已打包，是否完成打包?")
                    //.setIcon(R.mipmap.ic_launcher)
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            CommonUtil.showPress(PackDetailActivity.this);
                            ComplitePackTask complitePackTask = new ComplitePackTask(PackDetailActivity.this);
                            complitePackTask.execute();
                        }
                    })

                    .setNegativeButton("否", new DialogInterface.OnClickListener() {//添加取消
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            return;
                        }
                    })
                    .create();
            alertDialog.show();
        }
    }

    //打包事件
    private class ListViewClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (currentState == 1) {
                //打包
                if (position >= 0 && position < filterNotPackedDetailList.size()) {
                    packPosition = position;
                    PackDetailBean packDetailBean = filterNotPackedDetailList.get(packPosition);
                    alert_pack(packDetailBean.notpackCount);
                }
            } else {
                //取消打包
                PackBoxBean packBoxBean = packBoxBeanList.get(currentBox);
                if (position >= 0 && position < packBoxBean.packDetailBeanList.size()) {
                    packPosition = position;
                    AlertDialog alertDialog = new AlertDialog.Builder(PackDetailActivity.this)
                            //.setTitle("这是标题")
                            .setMessage("确认删除当前已打包配件?")
                            //.setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    unpack();
                                }
                            })

                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    packPosition = -1;
                                    //Toast.makeText(PackDetailActivity.this, "这是取消按钮", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .create();
                    alertDialog.show();

                }
            }
        }
    }

    //当前打包的选项
    int packPosition = -1;

    //自定义弹出窗口
    private void alert_pack(final String allCount) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_pack, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);

        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        //总数
        TextView tv_zms = (TextView) dialogView.findViewById(R.id.tv_zms);
        tv_zms.setText(String.valueOf(allCount));
        //打包数
        final TextView et_count = (TextView) dialogView.findViewById(R.id.et_count);
        et_count.setText(String.valueOf(allCount));
        TextView tv_equal = (TextView) dialogView.findViewById(R.id.tv_equal);
        //全部打包
        tv_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_count.setText(String.valueOf(allCount));
            }
        });
        //清空数量
        TextView tv_none = (TextView) dialogView.findViewById(R.id.tv_none);
        tv_none.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_count.setText("0");
            }
        });
        //提交打包
        TextView tv_ok = (TextView) dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                String packCount = et_count.getText().toString();
                pack(packCount);
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    //打包
    private void pack(String packCount) {
        if (packPosition != -1) {
            PackDetailBean packDetailBean = filterNotPackedDetailList.get(packPosition);
            CommonUtil.showPress(this);
            PackDetailTask packDetailTask = new PackDetailTask(packDetailBean, packCount, PackDetailActivity.this);
            packDetailTask.execute();
        }
    }

    //取消打包
    private void unpack() {
        if (packPosition != -1) {
            PackBoxBean packBoxBean = packBoxBeanList.get(currentBox);
            PackDetailBean packDetailBean = packBoxBean.packDetailBeanList.get(packPosition);
            CommonUtil.showPress(this);
            DeletePackDetailTask deletePackDetailTask = new DeletePackDetailTask(packDetailBean, PackDetailActivity.this);
            deletePackDetailTask.execute();
        }
    }

    //查询打包信息
    class QueryPackDetailTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryPackDetailTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                notPackedDetailList = WebServiceHelper_Pack.PACK_02(packInfobean.orderId);//未打包数据
                packBoxBeanList = WebServiceHelper_Pack.PACK_03(packInfobean.orderId, flag);//获取箱号列表
                //当没有打包时候，默认创建一个
                if (packBoxBeanList == null || packBoxBeanList.size() == 0) {
                    packBoxBeanList = new ArrayList<>();
                    PackBoxBean packBoxBean = new PackBoxBean();
                    packBoxBean.packingId = "-1";
                    packBoxBean.packingNo = "打包提交后自动生成";
                    packBoxBeanList.add(packBoxBean);
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindBox(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //删除箱号
    class DeletePackBoxTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        DeletePackBoxTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //删除
                WebServiceHelper_Pack.PACK_06(packBoxBeanList.get(currentBox).packingId);
                //查询结果
                notPackedDetailList = WebServiceHelper_Pack.PACK_02(packInfobean.orderId);
                packBoxBeanList = WebServiceHelper_Pack.PACK_03(packInfobean.orderId,flag);
                currentBox = packBoxBeanList.size() - 1;
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return "";
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindBox(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //打包某个配件到箱内
    class PackDetailTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private PackDetailBean currentPackDetailBean;
        private String packCount;

        PackDetailTask(PackDetailBean currentPackDetailBean, String packCount, Context context) {
            super();
            mcontext = context;
            this.currentPackDetailBean = currentPackDetailBean;
            this.packCount = packCount;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //打包
                PackBoxBean packBoxBean = packBoxBeanList.get(currentBox);
                WebServiceHelper_Pack.PACK_04(packBoxBean, packCount, currentPackDetailBean.dtlId, packInfobean.orderId);
                //查询结果
                notPackedDetailList = WebServiceHelper_Pack.PACK_02(packInfobean.orderId);
                packBoxBeanList = WebServiceHelper_Pack.PACK_03(packInfobean.orderId, flag);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return "";
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindBox(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //删除配件
    class DeletePackDetailTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private PackDetailBean currentPackDetailBean;

        DeletePackDetailTask(PackDetailBean currentPackDetailBean, Context context) {
            super();
            mcontext = context;
            this.currentPackDetailBean = currentPackDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                WebServiceHelper_Pack.PACK_07(currentPackDetailBean.dtlId);
                //查询结果
                notPackedDetailList = WebServiceHelper_Pack.PACK_02(packInfobean.orderId);
                packBoxBeanList = WebServiceHelper_Pack.PACK_03(packInfobean.orderId,flag);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return "";
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindBox(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //打包完成
    class ComplitePackTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        ComplitePackTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                WebServiceHelper_Pack.PACK_05(packInfobean.orderId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return "";
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Intent intent = new Intent(mcontext, PackInfoActivity.class);
                startActivity(intent);
                PackDetailActivity.this.finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //region 以下为扫码相关

    //初始化
    private void init(){
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    PartBean partBean = barCodeBean.partBean;
                    if (partBean == null) {
                        et_bar.setText("");
                        Toast.makeText(PackDetailActivity.this, "无效条码：" + barCode, Toast.LENGTH_LONG).show();
                    } else {
                        et_bar.setText(partBean.partCode);
                        filterData(partBean.partCode);
                        setButton(bt_unpack);
                    }
                } else {
                    et_bar.setText("");
                    Toast.makeText(PackDetailActivity.this, "无效配件条码", Toast.LENGTH_LONG).show();
                }

            } else {
                Toast.makeText(PackDetailActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(PackDetailActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(PackDetailActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion
}
